package cn.darkhorse.ticket.store.service.verification.impl;


import cn.darkhorse.ticket.store.dto.TicketProductDetailsDTO;
import cn.darkhorse.ticket.store.pojo.TicketInventorySurplus;
import cn.darkhorse.ticket.store.service.TicketInventoryService;
import cn.darkhorse.ticket.store.service.verification.ICalculationService.IQuantityRecordService;
import cn.darkhorse.ticket.store.service.verification.ICalculationService.MaterialUsage;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @description:
 * @author: mr.wang
 * @time: 2024/1/18 11:14
 */
@Service("increaseService")
public class BaseIncreaseServiceImpl extends MaterialUsage implements IQuantityRecordService {

	
	@Resource
	private TicketInventoryService inventoryService;
	
	/**
	 * 增减数量
	 * @param productList  key 仓库-产品  value 材料对象
	 */
	@Override
	public void changeQuantity(List<TicketProductDetailsDTO> productList) {
		Map<String, TicketProductDetailsDTO> productMap = surplusCheckDTOMap(productList);
		Map<String, TicketInventorySurplus> surplusMap = getSurplusMap();
		rwl.writeLock().lock();
		try {
			List<TicketInventorySurplus> surplusList = new ArrayList<>();
			Set<Map.Entry<String, TicketProductDetailsDTO>> entries = productMap.entrySet();
			for(Map.Entry<String, TicketProductDetailsDTO> entry:entries){
				String key = entry.getKey();
				TicketProductDetailsDTO dto = entry.getValue();
				TicketInventorySurplus surplus = surplusMap.get(key);
				if(null == surplus){
					surplus = new TicketInventorySurplus();
					surplus.setProductId(dto.getProductId());
					surplus.setWarehouseId(dto.getWarehouseInfoId());
					surplus.setWarehousingId(dto.getBusinessId());
					surplus.setUsege(BigDecimal.ZERO);
					surplus.setSurplus(dto.getQuantity());
					surplus.setTotal(dto.getQuantity());
				}else {
					surplus.setTotal(surplus.getTotal().add(dto.getQuantity()));
					surplus.setSurplus(surplus.getTotal().subtract(surplus.getUsege()));
					surplus.setWarehousingId(dto.getBusinessId());
					surplus.setOutboundId(null);
					surplus.setGmtCreate(LocalDateTime.now());
					surplus.setId(null);
				}
				surplus.setBusinessType(dto.getBusinessType());
				surplusList.add(surplus);
			}
			surplusService.saveBatch(surplusList);
			inventoryService.add(productList);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}finally {
			rwl.writeLock().unlock();
		}
	}
	
	
}
